package cn.hashq.netpostclient.handler.map;

import cn.hashq.netpostclient.constant.SessionKey;
import cn.hashq.netpostclient.dto.ProtoMsg;
import cn.hashq.netpostclient.session.ClientSession;
import cn.hashq.netpostclient.session.SessionMap;
import cn.hutool.core.util.IdUtil;
import com.google.protobuf.ByteString;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.Optional;

/**
 * 转发代理端口数据到服务端
 *
 * @author HashQ
 * @since 1.0
 */
@Slf4j
public class MapDataHandler extends ChannelInboundHandlerAdapter {

    private String sessionId;

    public MapDataHandler(String sessionId) {
        this.sessionId = sessionId;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        int length = buf.readableBytes();
        if (length == 0) {
            super.channelRead(ctx, msg);
            return;
        }
        byte[] data = new byte[length];
        buf.readBytes(data);
        ProtoMsg.DataPackage dataPackage = ProtoMsg.DataPackage.newBuilder()
                .setBytes(ByteString.copyFrom(data))
                .build();
        ProtoMsg.Message message = ProtoMsg.Message.newBuilder()
                .setSessionId(sessionId)
                .setType(ProtoMsg.HeadType.CLIENT_DATA_REDIRECT)
                .setDataPackage(dataPackage)
                .build();
        ClientSession session = SessionMap.inst().getSession(SessionKey.PROXY_SESSION_KEY);
        if (Objects.nonNull(session)) {
            session.writeAndFlush(message);
        } else {
            log.error("代理连接不存在");
            System.exit(0);
        }
    }
}
